package com.ruoyi.system.service.impl;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import com.ruoyi.system.mapper.SysFileMapper;
import org.apache.tomcat.jni.FileInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.model.*;
import java.io.IOException;
import java.sql.Date;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class OssServiceImpl {

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    public String uploadFile(MultipartFile file) throws IOException {
        // 生成文件路径
        String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = dateDir + "/" + UUID.randomUUID().toString() + extension;

        // 设置文件元信息
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(file.getContentType());
        metadata.setContentLength(file.getSize());

        // 上传文件
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getInputStream(), metadata);
        ossClient.putObject(putObjectRequest);

        // 返回文件访问URL
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }


    public void deleteFile(String fileUrl) {
        try {
            // 从URL中提取文件名
            String fileName = fileUrl.substring(fileUrl.indexOf(bucketName) + bucketName.length() + 1);
            // 删除文件
            ossClient.deleteObject(bucketName, fileName);
        } catch (Exception e) {
            throw new RuntimeException("删除文件失败", e);
        }
    }


//    public List<FileInfo> listFiles(String prefix) {
//        List<FileInfo> fileList = new ArrayList<>();
//        try {
//            // 创建列举对象请求，支持分页（最多1000条）
//            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName)
//                    .withPrefix(prefix)      // 前缀过滤
//                    .withMaxKeys(1000);      // 单次请求最大数量
//
//            // 分页获取所有对象
//            ObjectListing objectListing;
//            do {
//                objectListing = ossClient.listObjects(listObjectsRequest);
//                // 处理对象列表
//                for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
//                    fileList.add(new FileInfo(
//                            objectSummary.getKey(),
//                            objectSummary.getSize(),
//                            objectSummary.getLastModified()
//                    ));
//                }
//
//                // 设置下次请求的标记
//                listObjectsRequest.setMarker(objectListing.getNextMarker());
//            } while (objectListing.isTruncated());
//
//            return fileList;
//        } catch (Exception e) {
//            throw new RuntimeException("获取文件列表失败", e);
//        }
//    }
//
//    public String previewFile(String fileName) {
//        try {
//            // 检查文件是否存在
//            if (!ossClient.doesObjectExist(bucketName, fileName)) {
//                throw new IllegalArgumentException("文件不存在");
//            }
//
//            // 生成带签名的临时访问URL（30分钟有效期）
//            Date expiration = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
//            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileName)
//                    .withExpiration(expiration)
//                    .withMethod(HttpMethod.GET);
//
//            return ossClient.generatePresignedUrl(request).toString();
//        } catch (Exception e) {
//            throw new RuntimeException("生成预览链接失败", e);
//        }
//    }
}